const Koa = require('koa');
const KoaBody = require('koa-body');
const KoaRouter = require('koa-router');
const method = require("./method.js");
const config = require(`./src/config/${process.env.CONFIG}`);
const {request_error,request_success} = require("./common.js");

const app = new Koa();
app.use(KoaBody({ multipart: true }));

let router = new KoaRouter();

Object.keys(method).forEach((key) => {
    let fn = method[key];
    router.post(key, async (ctx,next) =>{
        try {
            let {data,msg} = await fn(ctx,ctx.request.body);
            await request_success(ctx,data,msg);
        } catch (error) {
            await request_error(ctx,error);      
        }
    });
});

const errorHandler = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.log(err);
    ctx.response.status = err.statusCode || err.status || 500;
    ctx.response.body = {
      message: err.message
    };
  }
};

app
  .use(errorHandler)
  .use(router.routes())
  .use(router.allowedMethods());

app.on('error', function (err) {
  console.log(err);
});

app.listen(config.port,()=>{
  console.log(`server start at port : ${config.port}`);
});